import React,{Component} from 'react';
import {Platform, ScrollView, StyleSheet, Text, View,Image,StatusBar,TouchableWithoutFeedback,Modal,SafeAreaView,
    PixelRatio} from 'react-native'
import {Container,Header,Tab,Tabs,ScrollableTab,TabContainer,Button,CheckBox,List, ListItem,Separator,Content,Form, Item, Input, Label } from 'native-base'
import {getTypesAndProduct} from '../api/api'
import BasePage from '../base/BasePage'
import { default as ListView } from '../components/CustomList/index'
import ScrollableTabView,{ScrollableTabBar} from 'react-native-scrollable-tab-view'

const pixHeight = 1 / PixelRatio.get();

export default class HomeNative extends BasePage {

	constructor(props) {
	  super(props);
	
	  this.state = {
		  tabs:[],
          respData:[],
		  checked:false,
		  modalVisible:false,
          currentTab:0,
          loading:false,
          firstInit:true
	  };
	  this.showModal = () => {
			this.setState({ modalVisible: true })	
		}
	}

    onSwitchChange = (index) => {
        // console.log('[state.checked ==> value]',index)
		let resp = this.state.respData;
		let product = resp[this.state.currentTab].productList[index]

        product.checked = product.checked?product.checked:false;
        product.checked = !product.checked
        resp[this.state.currentTab].productList[index] = product;
        this.setState({
            respData: resp,
        });
    };

    sleep = (time) => new Promise(resolve => setTimeout(() => resolve(), time));

    onFetch = async (page = 1, startFetch, abortFetch) => {
        try {
            let pageLimit = 100;
            await this.sleep(10);

            console.log(111,this.state.currentTab)
            // if(this.state.respData.length == 0) {
                // console.log(112,this.state.respData.length)
                await this.loadData();
            // }
            console.log(222)
            let productList = this.state.respData[this.state.currentTab].productList;
            console.log(333,productList)
            productList.map((m) => {
            	m.checked = false;
			})
            if(this.state.firstInit) {
                this.setState({currentTab:1,firstInit:false})
            }
            console.log('[productList]',productList)
            startFetch(productList, pageLimit);
        } catch (err) {
            abortFetch(); //manually stop the refresh or pagination if it encounters network error
        }
    }

	renderItem = (product,index) => {
	    return (
            <View  style={styles.tablist}>
                <View style={styles.list_top}>
                    <Text style={[styles.top_left,styles.green]}>{product.name}</Text>
                    <Text style={styles.top_right}>预估：<Text style={styles.green}>{product.planNum}{product.unit}</Text></Text>
                </View>
                <View style={styles.list_center}>
                    <Text style={styles.center_a1}>数量：<Text style={styles.red}>{product.actualNum?product.actualNum:0}{product.unit}</Text></Text>
                    <Text style={styles.center_a1}>采购价：<Text style={styles.red}>￥{product.actualPrice?product.actualPrice:0}</Text></Text>
                    <Text style={styles.center_a1}>总价：<Text style={styles.red}>￥{product.actualNum * product.actualPrice}</Text></Text>
                </View>
                <View style={styles.list_center}>
                    <Text style={styles.center_a1}>销售价：<Text style={commonStyle.orange}>￥{product.salePrice?product.salePrice:0}</Text></Text>
                    <Text style={styles.center_a1}>加价：<Text style={commonStyle.orange}>+{product.increaseAmount?product.increaseAmount:0}</Text></Text>
                    <Text style={styles.center_a1}>差价率：<Text style={commonStyle.orange}>{product.increaseRatio?product.increaseRatio:0}%</Text></Text>
                </View>
                <View style={styles.list_bottom}>
                    <TouchableWithoutFeedback  onPress={()=>{this.onSwitchChange(index)}}>
                        <View style={styles.bottom_left}>
                            <CheckBox checked={product.checked?product.checked:false} style={styles.bottom_checkbox} onPress={()=>{this.onSwitchChange(index)}}/>
                            <Text style={styles.gray}>装车</Text>
                        </View>
                    </TouchableWithoutFeedback >
                    <Button style={styles.btn_green} onPress={this.showModal} ><Text style={styles.btn_white}>点击输入</Text></Button>
                </View>
            </View>
        )
    }

    _Separator = () => {
        return <View style={{height:pixHeight,backgroundColor:'#ddd',}}/>
    }

	renderPage() {
		return ( 
			<Container style={styles.container}>
				{/*<Tabs renderTabBar={()=> <ScrollableTab />} tabBarUnderlineStyle={{backgroundColor: '#0abe73',height:ScreenUtil.scaleHeight(1),*/}
			{/*width:ScreenUtil.scaleSize(100)}} onChangeTab={(tabs)=> {this.setState({currentTab:tabs.i})}}>*/}
					{/*{*/}
						{/*this.state.tabs.map((m,index) => {*/}
							{/*return (*/}
								{/*<Tab heading={m} key={index} tabStyle={styles.tabStyle} activeTabStyle={{backgroundColor:'white'}} textStyle={{color:'#333'}} */}
								{/*activeTextStyle={{color:'#0abe73'}}>*/}
									{/*<ListView refreshable={false} onFetch={this.onFetch} renderItem={this.renderItem} separator={this._Separator}*/}
											  {/*keyExtractor={(item, index) => `${index}`} extraData={this.state}/>*/}
								{/*</Tab>*/}
							{/*)*/}
						{/*})*/}
					{/*}*/}
				{/*</Tabs>*/}
				<ScrollableTabView prerenderingSiblingsNumber={1} onChangeTab={(tabs)=> {this.setState({currentTab:tabs.i})}} renderTabBar={()=><ScrollableTabBar/>}>
                    {
                        this.state.tabs.map((m,index) => {
                            return (
                                <View tabLabel={m} key={index} tabStyle={styles.tabStyle} activeTabStyle={{backgroundColor:'white'}} textStyle={{color:'#333'}}
                                     activeTextStyle={{color:'#0abe73'}} >
                                    <ListView refreshable={false} onFetch={this.onFetch} renderItem={this.renderItem} separator={this._Separator}
                                              keyExtractor={(item, index) => `${index}`} extraData={this.state}/>
                                </View>
                            )
                        })
                    }
				</ScrollableTabView>
				<View >
					<Modal
						animationType="fade"
						transparent={true}
						visible={this.state.modalVisible}
						onRequestClose={() => {
							alert("Modal has been closed.");
							this.setState({modalVisible:false})
						}}
						style={styles.modalbox} 
						> 
						<TouchableWithoutFeedback  onPress={()=>{this.setState({modalVisible:false})}}>
							<View style={styles.modal_container}>
								<View style={styles.modal_view}> 								
									<Form style={{ alignItems: 'center',justifyContent:'center',}}>
										<Item  inlineLabel>
											<Label style={styles.modal_label}>数量</Label>
											<Input style={styles.modal_input} placeholder='请输入' placeholderTextColor='#ddd' />
										</Item>
										<Item inlineLabel>
											<Label style={styles.modal_label}>采购价</Label>
											<Input style={styles.modal_input} placeholder='请输入' placeholderTextColor='#ddd' />
										</Item>
										<Item inlineLabel last>
											<Label style={styles.modal_label}>销售价</Label>
											<Input style={styles.modal_input} placeholder='请输入' placeholderTextColor='#ddd' />
										</Item>
									</Form>
									<View style={styles.modal_btns}>
										<Button style={styles.modal_btn} onPress={()=>{this.setState({modalVisible:false})}} ><Text style={styles.white} >取消</Text></Button>	
										<Button style={styles.modal_btn} onPress={()=>{this.setState({modalVisible:false})}} ><Text style={styles.white} >提交</Text></Button>	
									</View>
														
								</View>
							</View>
						</TouchableWithoutFeedback>
					</Modal>
					</View>
			</Container>
		) 
	}

    componentWillMount() {
        this.loadData()
    }

    async loadData() {
        if(this.state.loading) return
        this.setState({loading:true})
        let resp = await getTypesAndProduct();
        let typeList = [];
        resp.typeList.map(m => {
            typeList.push(m.name)
        })
		console.log('[typeList]',typeList)
        this.setState({tabs:typeList,respData:resp.typeList})
        this.setState({loading:false})
    }

}

const styles = StyleSheet.create({
	container:{
		flex: 1, 
		backgroundColor: 'white',
	},
	tabStyle:{
		backgroundColor:'white',
	},
	green:{
		color:'#0abe73',
	},
	red:{
		color:'#f30',
	},
	orange:{
		color:'#f80',
	},
	gray:{
		color:'#999',
	},
	white:{
		color:'#fff',
		fontSize:ScreenUtil.setSpText2(16),
	},
	tablist:{
		paddingTop:ScreenUtil.scaleHeight(10),
		paddingLeft:ScreenUtil.scaleSize(10),
		paddingRight:ScreenUtil.scaleSize(10),
		paddingBottom:ScreenUtil.scaleHeight(20),
	},
	list_top:{
		flexDirection:'row',
		justifyContent: 'space-between',
		fontSize:ScreenUtil.setSpText2(14),
		marginBottom:ScreenUtil.scaleHeight(10),
	},
	top_left:{
		fontSize:ScreenUtil.setSpText2(16),
	},
	top_right:{
		color:'#999',
	},
	list_center:{
		flexDirection:'row',
		marginBottom:ScreenUtil.scaleHeight(10),
	},
	center_a1:{
		marginRight:ScreenUtil.scaleSize(10),
		color:'#999',
	},
	list_bottom:{
		flexDirection:'row',
		justifyContent: 'space-between',
	},
	bottom_left:{
		flexDirection:'row',
		alignItems:'center',
	},
	bottom_checkbox:{
		marginRight:ScreenUtil.scaleSize(20),
	},
	btn_green:{
		height:30,
		backgroundColor:'#0abe73',
		padding:10,
	},
	btn_white:{
		color:'#fff',
		fontSize:ScreenUtil.setSpText2(14),
	},
	footbtn:{
		borderRadius:0,
	},
	modal_btn:{
		height:ScreenUtil.scaleHeight(40),
		backgroundColor:'#0abe73',
		padding:10,
		alignItems:'center',
		justifyContent:'center',
		flex:2,
		margin:10,
	},
	modal_container:{
		flex: 1,
		backgroundColor:'rgba(0, 0, 0, 0.5)',
		justifyContent: 'center', 
		padding: 20
	},
	modal_view:{
		height:ScreenUtil.scaleHeight(260),
		borderRadius: 10, 
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor:'#fff', 
		padding: 20,
	},
	modal_label:{
		width:ScreenUtil.scaleSize(78),
		fontSize:ScreenUtil.setSpText2(16),
	},
	modal_input:{
		fontSize:ScreenUtil.setSpText2(16),
	},
	modal_btns:{
		flexDirection:'row', 
		alignItems: 'center',
		justifyContent:'space-between',
		marginTop:ScreenUtil.scaleHeight(10),
	}
})